import React, { PureComponent } from 'react'
import { Page , Filter} from 'components'
import { Table, Input, InputNumber, Select, Popconfirm, Form, Button } from 'antd'
import { connect } from 'dva'

const EditableContext = React.createContext()

class EditableCell extends PureComponent {

	renderCell = ({ getFieldDecorator }) => {
	
	    const {editing, dataIndex, title, input, record, index, children, ...restProps } = this.props
	    
	    return (
	      <td key={`${r'${dataIndex}_${index}'}`} {...restProps}>
	        {editing ? (
	          <Form.Item style={{ margin: 0 }}>
	            {getFieldDecorator(dataIndex, {
	              rules: [
	                {
	                  required: true,
	                  message: `请输入${r'${title}'}!`,
	                },
	              ],
	              initialValue: record[dataIndex],
	            })(input)}
	          </Form.Item>
	        ) : (
	          children
	        )}
	      </td>
	    )
  	}

	render() {
		return (
			<EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
		)
	}
}

@connect(({ ${namespace}, loading }) => ({${namespace}, loading}))
class EditableTable extends PureComponent {

	render() {
		const { ${namespace}, dispatch, loading, location ,form} = this.props

		const { list, pagination, editingKey, editType, <#list forms as form><#if (form.type=='Select')>${form.name}Tree, </#if></#list>} = ${namespace}

		const isEditing = record => record.id === editingKey

		const edit = (key) => {
			dispatch({type:'${namespace}/updateState',payload:{editingKey: key,editType:'update'}})
		}

		const cancel = () => {
			dispatch({type:'${namespace}/updateState',payload:{editingKey: ''}})
		}

		const save=(form, record)=>{
			form.validateFields((error, values) => {
				if (error) {
					return
				}
				dispatch({
					type: `${namespace}/${r'${editType}'}`,
					payload: {...record,...values},
				}).then(() => {
					cancel()
					if(${r'${editType}'}==='create'){
						handleRefresh()
					}else{
						handleRefresh({page:pagination.current})
					}
				})
			})
		}


		const handleDelete = key => {
			dispatch({
				type: '${namespace}/remove',
				payload: { id: key },
			}).then(() => {
				handleRefresh({page:list.length === 1 && pagination.current > 1? pagination.current - 1: pagination.current})
			})
		}

		const handleRefresh = newQuery => {
			dispatch({type:'${namespace}/query',payload:{...filterItem,...newQuery,pageSize:pagination.pageSize}})
		}

		const components = {body: {cell: EditableCell } }

		const columns = [<#list columns as col>
			{
				title:'${col.title}',
				dataIndex: '${col.name}',<#if (col.align)>
				align:'left',</#if>
				onCell: record => ({
					record,
		            input: <#if (col.formType=='Select')><Select style={{width:'100%'}}>${col.name}Tree.map((i)=>(<Select.Option key={i.title} value={i.title}>{i.title}</Select.Option>))</Select><#else><${col.formType} /></#if>,
		            title: '${col.title}',
		            dataIndex: '${col.name}',
		            editing: isEditing(record),
				})
			},</#list>
			{
				title: '操作',
			    dataIndex: 'id',
			    render: (text, record) => {
					const editable = isEditing(record)
					return editable ? (
					<span>
						<EditableContext.Consumer>
							{form => (
								<a onClick={() => save(form,record)} style={{ marginRight: 8 }} >保存</a>
							)}
						</EditableContext.Consumer>
						<Popconfirm title="确认取消?" onConfirm={() => cancel()} >
							<a>取消</a>
						</Popconfirm>
					</span>
					) : (
					<div>
						<a disabled={editingKey !== ''} onClick={() => edit(record.id)} style={{ marginRight: 8 }}>编辑</a>
						<Popconfirm title="确认删除?" onConfirm={() => handleDelete(record.id)} >
							<a>删除</a>
						</Popconfirm>
					</div>
					)
				},
			}]
    
		const filterProps = {
			filterItemValues:filterItem,
			filterItemColumns:[<#list filters as filter>
				{
					type: '${filter.type}',
					label: '${filter.title}',
					target: '${filter.name}',
					tip: '輸入${filter.title}',
					key: '${filter.name}',
				},</#list>
			],
			onFilterChange(fields) {
				dispatch({
					type: '${namespace}/updateState',
					payload: { filterItem: fields },
				})
				dispatch({
					type: '${namespace}/query',
					payload: {
						page: 1,
						pageSize: pagination.pageSize,
						...fields
					},
				})
			},
			btns:[
				{
					text:'新增',
					handle:()=>{
						let arr=[{id:0},...list]
	      				dispatch({type:'${namespace}/updateState',payload:{list: arr,editingKey: 0,editType:'create'}})
					}
				}
			]
		}
    
	    const listProps = {
	      components:components,
	      bordered:true,
	      rowKey:'id',
	      dataSource: list,
	      columns:columns,
	      loading: loading.effects['medicine/query'],
	      pagination:pagination,
	      onChange(page) {
	        cancel()
	        dispatch({
	          type: 'medicine/query',
	          payload: {
	            page: page.current,
	            pageSize: page.pageSize,
	            ...fields
	          },
	        })
	      },
	    }

	    return (
	      <Page inner>
		      <Filter {...filterProps} />
		      <EditableContext.Provider value={form}>
		        <Table {...listProps}/>
		      </EditableContext.Provider>
	      </Page>
	    )
	}
}
export default Form.create()(EditableTable)
